package com.thinksns.sociax.t4.service;

import android.app.IntentService;
import android.content.Intent;

import com.thinksns.sociax.t4.android.Thinksns;
import com.thinksns.sociax.t4.model.ModelChannel;
import com.thinksns.sociax.t4.model.ModelSearchUser;
import com.thinksns.sociax.thinksnsbase.exception.ApiException;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AddRcdFriendService extends IntentService {
    private static final int TYPE_FOLLOW = 1; // 1表示要关注

    private List<ModelSearchUser> users;
    private List<ModelChannel> channels;
    private final ExecutorService single = Executors.newSingleThreadExecutor();

    private String uids = ""; //需要关注人的uid，以逗号连接
    private String channelIds = ""; //需要关注频道的uid，以逗号连接

    public AddRcdFriendService() {
        super("AddRcdFriendService");
    }

    public AddRcdFriendService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        final Thinksns app = (Thinksns) getApplication();
        // 用户关注
        users = (List<ModelSearchUser>) intent.getSerializableExtra("users");
        if (users != null) {
            for (ModelSearchUser user : users) {
                if (user.getFollowing().equals(TYPE_FOLLOW + "")) {  // 如果为1表示要关注
                    uids += user.getUid() + ",";
                }
            }
            if (uids.length() > 0) {
                uids = uids.substring(0, uids.length() - 1); // 去除最后一位逗号
                single.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            app.getUsers().changeFollowing(uids, TYPE_FOLLOW);
                        } catch (ApiException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

        }

        // 频道关注
        channels = (List<ModelChannel>) intent.getSerializableExtra("channel");
        if (channels != null) {
            for (final ModelChannel channel : channels) {
                if (channel.getIs_follow() == TYPE_FOLLOW) {
                    channelIds = channel.getIs_follow() + ",";
                }
            }
            if (channelIds.length() > 0) {
                channelIds = channelIds.substring(0, channelIds.length() - 1);
                single.execute(new Runnable() {
                    @Override
                    public void run() {
                        app.getChannelApi().changeFollow(channelIds, TYPE_FOLLOW + "");
                    }
                });
            }
        }
    }
}
